package com.zhiche.lisa.tms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zhiche.lisa.core.enums.IntegrationURIEnum;
import com.zhiche.lisa.core.enums.SystemEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.tms.controller.PodReasonController;
import com.zhiche.lisa.tms.dao.mapper.AbnormalPodReasonMapper;
import com.zhiche.lisa.tms.dao.model.AbnormalPodReason;
import com.zhiche.lisa.tms.dao.model.PodReason;
import com.zhiche.lisa.tms.dto.PodReasonDTO;
import com.zhiche.lisa.tms.dto.ReceiptDTO;
import com.zhiche.lisa.tms.service.AbnormalPodReasonService;
import com.zhiche.lisa.tms.service.PodReasonService;
import com.zhiche.lisa.tms.vo.ReceiptVO;
import com.zhiche.lisa.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : suohao
 * Date: 2019/7/29
 */
@Service
@Transactional
public class AbnormalPodReasonServiceImpl extends ServiceImpl<AbnormalPodReasonMapper, AbnormalPodReason> implements AbnormalPodReasonService {

    private static final Logger logger = LoggerFactory.getLogger(AbnormalPodReasonServiceImpl.class);

    @Autowired
    private PodReasonService podReasonService;
    @Value("${integration.podReasonToOtm}")
    private String podReasonToOtm;
    @Value("${integration.url}")
    private String integrationUrl;
    @Value("${logRedis.isTest}")
    private boolean isTest;


    @Override
    public List getFirstAbnormalPodReason() {
        EntityWrapper<AbnormalPodReason> ew = new EntityWrapper<>();
        ArrayList<Object> list = new ArrayList<>();
        list.add("订单异常");
        list.add("运力原因");
        list.add("事故买断");
        list.add("补单");
        list.add("无运单");
        list.add("连带压单");
        list.add("运营过程问题");
        ew.notIn("abnormal_pod_reason",list);
        return baseMapper.selectPodReasonNoTenant(ew);
    }

    @Override
    public List getSecondAbnormalPodReason(String abnormalPodReason) {

        List list= baseMapper.getSecondPodReasonNoTenant(abnormalPodReason);
        return list;
    }

    @Override
    public void podReasonToOtm(ReceiptVO<ReceiptDTO> receiptVO, HttpServletRequest request) {
        for (ReceiptDTO receiptDTO : receiptVO.getReceiptDTOs()) {

            if (Objects.isNull(receiptDTO)){
                throw new BaseException("请求参数不能为空");
            }
            if (StringUtils.isEmpty(receiptVO.getAbnormalPodReason())){
                throw new BaseException("异常原因不能为空");
            }
            if (StringUtils.isEmpty(receiptVO.getReasonDes())){
                throw new BaseException("子异常原因不能为空");
            }
            //查询异常信息表
            AbnormalPodReason abnormalPodReason=baseMapper.queryReasonNoTenant(receiptVO.getAbnormalPodReason(),receiptVO.getReasonDes());

            //插入订单回单异常表
            PodReason podReason = new PodReason();
            podReason.setAbnormalPodReasonId(abnormalPodReason.getId());
            podReason.setOrderItemId(receiptDTO.getId());
            podReason.setCode("PDR"+ RandomUtil.game(8));
            podReason.setReason(receiptVO.getReason());
            String name = request.getUserPrincipal().getName();
            podReason.setCreator(name);
            podReason.setGmtUpdate(new Date());
            podReason.setGmtCreate(new Date());
            podReasonService.insert(podReason);

            PodReasonDTO podReasonDTO = new PodReasonDTO();
            if (Objects.nonNull(abnormalPodReason)){
                podReasonDTO.setRecordDate(new Date());
                podReasonDTO.setOrderGid("ULC/ZC."+receiptDTO.getOrderNo());
                //podReasonDTO.setHandlerStatus(receiptVO.getReason());
                podReasonDTO.setDetails(receiptVO.getReason());
                podReasonDTO.setAbnormalPodReason("ULC/ZC."+abnormalPodReason.getAbnormalPodReasonXid());
                podReasonDTO.setPodReasonXid(podReason.getCode());
            }

            //传送OTM
                String jsonParam = JSONObject.toJSONString(podReasonDTO);
            try {
                logger.info("异常回单传otm url:{},param:{}", integrationUrl+podReasonToOtm, jsonParam);
                String postJson = HttpClientUtil.postJson(integrationUrl+podReasonToOtm,
                        null, jsonParam, 60000);
                RedisLogUtil.addSysLogs(SystemEnum.OMS.getCode(),SystemEnum.INTEGRATION.getCode(),"异常回单原因"+podReasonDTO.getOrderGid(), jsonParam,"/otm/podReasonToOtm",1,1,null,isTest);
                if (StringUtils.isEmpty(postJson)){
                    throw new BaseException("异常回单传otm 连接超时");
                }
                JSONObject jsonObject = JSONObject.parseObject(postJson);
                int code = (int) jsonObject.get("code");
                String data = (String) jsonObject.get("data");
                if (code==0 ){
                    if (!StringUtils.isEmpty(data)){
                        JSONObject otmObject = JSONObject.parseObject(data);
                        String messageType = (String) otmObject.get("messageType");
                        String message = (String) otmObject.get("message");
                        if ("error".equals(messageType)){
                            throw new BaseException(receiptDTO.getOrderNo()+"异常回单传otm 异常原因 ："+message);
                        }
                    }
                }else {
                    throw new BaseException("异常回单传otm 连接失败 ");
                }
            }catch (Exception e){
                throw new BaseException(e.getMessage());
            }
        }
    }


}
